<!--这是上传视频组件-->
<template>
	<div style="padding-bottom: 30px;">
		<div class="addBox">
			<h3><span>上传视频</span></h3>
			<div style="margin: 0 20px;">
				<p style="line-height: 36px;">已上传列表：</p>
				<table v-loading="listLoading">
					<tr>
						<th>上传编号</th>
            <th>明细名称</th>
            <th>视频ID</th>
            <th>排序</th>
						<th>操作</th>
					</tr>
          <tr v-for="(item,index) in vedioList" :key="index">

				  <td>{{item.courseDetailId}}</td>
				  <td>{{item.videoName}}</td>
				  <td>{{item.pfVideoId}}</td>
				  <td>{{item.sort}}</td>
			  	<td>
              <el-button type="danger" size="mini" @click="deleteVideo(item.courseDetailId, item.pfVideoId)">删除</el-button>
              <el-button type="primary" size="mini" @click="linkToEdit(item.courseDetailId,index)">编辑</el-button>
            	</td>
		  </tr>
					<!-- <tr v-for="item in uploadList" :key="item.id">
						<td>{{ item.num }}</td>
						<td>{{ item.name }}</td>
						<td>{{ item.id }}</td>
            <td>{{ item.vSort }}</td>
						<td>
              <el-button type="danger" size="mini" @click="deleteVideo">删除</el-button>
              <el-button type="primary" size="mini">编辑</el-button>
            </td>
					</tr> -->
				</table>
        <code>
          <svg-icon icon-class="message" style="margin-right:10px;color:red;font-size:20px;"></svg-icon>
          提示：
          视频格式只支持MP4格式
        </code>
        <el-upload
          class="upload-demo"
          ref="upload"
          action=""
          :on-change="onChange"
          :before-upload="beforeUpload"
          :show-file-list="false"
          :data="formData"
          :auto-upload="false">
          <el-button slot="trigger" size="small" type="primary" :disabled="btnLoading">选取文件</el-button>
          <el-button style="margin-left: 10px;" size="small" v-loading="btnLoading" :disabled="btnLoading" type="success" @click="submitUpload">上传到服务器</el-button>
          <el-button size="small" type="danger" @click="cancelUpload">取消上传</el-button>
        </el-upload>
			</div>
			<div style="margin: 0 20px;">
				<p style="line-height: 36px;">上传进度：</p>
				<table>
					<tr>
						<th>视频名称</th>
						<th>上传进度</th>
						<th>上传状态</th>
					</tr>
					<tr v-show="uploadShow">
						<td>{{ fileName }}</td>
						<td>{{ percent }}</td>
						<td>{{ status }}</td>
					</tr>
				</table>
      </div>
    </div>
    <editUploadVideo v-show="isShowEdit" @hideEdit="hideEdit" :id="data.courseDetailId" @getData="getUpdateData"></editUploadVideo>
  </div>
</template>
<script>
  import { getUploadToken } from '@/api/qiniu'
  import { getCourseVedio, setCourseVedio, deleteTxFile, convertTxVodFile } from '@/api/courseDetail'
  import editUploadVideo from './editUploadVideo'
  import $ from 'jquery'
  import data from '../../svg-icons/generateIconsView'
import { getVideoPlatformType } from '@/api/company'
  const postForm = {
    audioName: null,
    qiniuObject: null
  }

  const uploadList = [] // 储存上传的视频数据

  export default {
    components: {
      editUploadVideo
    },
    data() {
      return {
        postForm,
        uploadList,
        uploadData: {},
        formData: {
          token: null
          // key: null
        },
        fileName: null, // 上传视频的文件名
        percent: null, // 进度
        status: null,
        listShow: false, // 是否显示上传列表
        uploadShow: true, // 是否显示上传文件的状态
        btnLoading: false,
        listLoading: false,
        courseId: null,
        isShowEdit: false, // 是否显示编辑视频组件
        cos: null,
        taskId: null,
        vedioList: null,
        data: {
          courseDetailId: null,
          courseId: null,
          videoName: null,
          pfVideoId: null,
          videoSrc: null,
          videoUrl: null,
          sort: null,
          opType: null
        },
        editIndex: null
      }
    },
    created() {
      // 刷新列表
      this.courseId = this.$route.params.courseId
      this.listLoading = true
      getCourseVedio(this.$route.params.courseId)
        .then(res => {
          this.listLoading = false
          this.vedioList = res.data.data
        })
        .catch(err => {
          this.listLoading = false
          console.log(err)
        })
    },
    methods: {
      hideEdit(msg) {
        this.isShowEdit = msg
      },
      getUpdateData(data) {
        getCourseVedio(this.$route.params.courseId)
          .then(res => {
            this.vedioList = res.data.data
          })
          .catch(err => {
            console.log(err)
          })
      },
      linkToEdit(id, index) {
        this.data.courseDetailId = id
        this.isShowEdit = true
        this.editIndex = index
      },
      deleteVideo(id, pfVideoId) {
        this.$confirm('确定删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 删除成功
          this.data.courseDetailId = id
          this.data.opType = 3
          this.listLoading = true
          setCourseVedio(this.data).then(res => {
            this.listLoading = false

            // 删除服务器视频信息
            deleteTxFile(pfVideoId).then(res => {
              if (res.data.data['code'] != 0) {
                this.$message({
                  type: 'success',
                  message: '云服务器同步删除失败'
                })
              }
            })

            // 刷新列表
            getCourseVedio(this.courseId)
              .then(res => {
                this.vedioList = res.data.data
                console.log(this.vedioList)
              })
              .catch(err => {
                console.log(err)
              })
          })

          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      beforeUpload(file) {
        // this.formData.key = 'courses/' + this.courseId + '/' + file.name
        this.percent = '0%'
        this.status = '开始上传'
      },
      onChange(file, filelist) {
        const isMP4 = file.raw.type == 'video/mp4'
        const isFu = /[\/]|[\?]|[\:]|[\*]|[\"]|[<]|[>]|[,]/.test(file.name)
        // const maxSize = file.raw.size / 1024 / 1024 < 100
        if (!isMP4) {
          this.$message({
            message: '视频必须为 MP4 格式',
            type: 'warning'
          })
          return false
        }
        if (isFu) {
          this.$message({
            message: '视频文件名不得包含 / : * ? " < > , 等字符',
            type: 'warning'
          })
          return false
        }
        this.fileName = file.name
        this.uploadData = file
        this.uploadShow = true
      },
      cancelUpload() {
        qcVideo.ugcUploader.cancel({
          cos: this.cos,
          taskId: this.taskId
        })
        this.btnLoading = false
      },
      submitUpload() {
        if (this.fileName == null) {
          this.$message({
            message: '请选择要上传的视频文件',
            type: 'warning'
          })
          return false
        }

        getVideoPlatformType().then(res => {
          if (res.data.data[0].videoPlatformType == 0) {
            this.$confirm('已切换到乐视视频上传，请退出当前页面，重新点击上传视频！?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.$router.push({ path: `/courses/${this.courseId}/uploadVideoLeShi` })
            }).catch(() => {
              this.$router.push({ path: `/courses/${this.courseId}/uploadVideoLeShi` })
            })
            return
          }

          this.btnLoading = true
          //this.$refs.upload.submit()
          const $this = this
          qcVideo.ugcUploader.start({ // 上传视频
            videoFile: this.uploadData.raw, // 视频，类型为 File
            getSignature: this.getSignature, // 前文中所述的获取上传签名的函数
            error(result) { // 上传失败时的回调函数
              $this.status = '上传失败的原因：' + result.msg
            },
            progress(result) {
              $this.cos = result.cos
              $this.taskId = result.taskId
              $this.percent = (Math.floor(result.shacurr * 100) > 1 ? (Math.floor(result.shacurr * 100) - 1) : Math.floor(result.shacurr * 100)) + '%'
              $this.status = '上传中'
            },
            finish(result) { // 上传成功时的回调函数
              $this.percent = 100 + '%'
              $this.status = '上传成功'
              $this.btnLoading = false
              // 清空信息
              $this.fileName = null
              $this.percent = null
              $this.status = null
              $this.uploadShow = false
              // 新增信息
              $this.data.courseDetailId = 1
              $this.data.courseId = $this.courseId
              $this.data.videoName = result.videoName
              $this.data.pfVideoId = result.fileId
              $this.data.videoSrc = 2
              $this.data.videoUrl = result.videoUrl
              $this.data.sort = 0
              $this.data.opType = 1
              setCourseVedio($this.data).then(res => {
                convertTxVodFile($this.data.pfVideoId).then(res => {
                  console.log(res.data.data)
                })
                getCourseVedio($this.courseId)
                  .then(res => {
                    $this.vedioList = res.data.data
                  })
                  .catch(err => {
                    console.log(err)
                  })
              }
              )
            },
            success(result) {
              $this.cos = null
            }
          })
        })
      },
      close() { // 关闭当前窗口
        console.log(this.$route)
        var obj = {
          name: this.$route.name,
          path: this.$router.path,
          title: this.$route.meta.title
        }
        this.$store.dispatch('delVisitedViews', obj).then((views) => {
          const latestView = views.slice(-1)[0]
          console.log(latestView)
          if (latestView) {
            this.$router.push(latestView.path)
          } else {
            this.$router.push('/')
          }
        })
      }
    }
  }
</script>

<style scoped>
	p,h3 {margin:0;padding:0}
	h3{
		font-weight: 500;
		font-size: 14px;
		height: 36px;
		background: #eee;
		border-bottom: 1px solid #ddd;
		padding: 0 20px;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}
	.addBox {
		width: 100%;
		overflow: auto;
		background: #fff;
	}
	table,tr,td,th{
		border: 1px solid #ddd;
		border-collapse: collapse;
		border-spacing: 0;
		text-align: center;
	}
	th{
		background: #f5fafe;
	}
	table{
		font-size: 12px;
		color: #333;
		width: 100%;
		line-height: 36px;
		margin-bottom: 20px;
	}
	b{
    	cursor: pointer;
    	font-weight: 500;
    }
	b:hover{
		color: #0A76A4;
  }
</style>
